<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <%@ include file="../../share/layoutIndex.jsp"%> 
	
    <link href="stoneframe/scripts/plugins/dataTables1.10.15/media/css/jquery.dataTables.css" rel="stylesheet" />
    <style type="text/css">
        #tip {
            background-color: #fff;
            padding:0 10px;
            border: 1px solid silver;
            box-shadow: 3px 4px 3px 0px silver;
            position: absolute;
            font-size: 12px;
            right: 20px;
            top: 40px;
            border-radius: 3px;
            line-height: 36px;
            width:400px;
        }
    </style>
    <script src="http://webapi.amap.com/maps?v=1.3&key=857fce8ded133c1a7e2ab20d5c626dcd&&plugin=AMap.Scale,AMap.OverView,AMap.ToolBar,AMap.Autocomplete,AMap.PolyEditor,AMap.CircleEditor,AMap.MouseTool"></script>
    <script src="stoneframe/scripts/plugins/dataTables1.10.15/dataTables1.10.15/media/js/jquery.dataTables.js"></script>
  </head>
<body>
<div id="container"></div>

<div id="tip">
    <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal">绘制围栏</button>

    <table id="example" class="table acelistTable"> 
    <thead> 
     <tr> 
      <th style="width:90px;"></th> 
      <th>用户编码</th> 
      <th>围栏名称</th> 
     </tr> 
    </thead> 
    <tbody>
    </tbody> 
   </table> 
</div>

<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="text-align:center;">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
                <div class="btn-group">
                    <button type="button" class="btn btn-default" id="btnRect">矩形</button>
                    <button type="button" class="btn btn-default" id="btnCircle">圆形</button>
                    <button type="button" class="btn btn-default" id="btnArea">多边形</button>
                </div>
				</h4>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>

<!-- 添加围栏模态框（Modal） -->
<div class="modal fade" id="areaModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" 
						aria-hidden="true">×
				</button>
				<h4 class="modal-title" id="H1">
					添加围栏
				</h4>
			</div>
			<div class="modal-body">
				<form class="form-horizontal" role="form" id="form1">
                    <input id="id" type="hidden" value=" " />
                    <input id="vertexes" type="hidden" />
                    <input id="source_map_type" type="hidden" value="2" />
                    
                    <div class="form-group">
		                <label for="uid" class="col-sm-3 control-label"><span style="color:red">*</span>用户编码：</label>
		                <div class="col-sm-9">
			                <input type="text" class="form-control" id="uid" placeholder="请输入用户编码">
		                </div>
	                </div>
	                <div class="form-group">
		                <label for="firstname" class="col-sm-3 control-label"><span style="color:red">*</span>围栏名称：</label>
		                <div class="col-sm-9">
			                <input type="text" class="form-control" id="name" placeholder="请输入围栏名称">
		                </div>
	                </div>
	                <div class="form-group">
		                <label for="lastname" class="col-sm-3 control-label">围栏类型：</label>
		                <div class="col-sm-9">
                            <input id="shape_type" type="hidden" />
			                <input type="text" class="form-control" id="shape_typeVal" placeholder="请输入围栏类型" disabled="disabled">
		                </div>
	                </div>
                    <div class="form-group">
		                <label for="lastname" class="col-sm-3 control-label">报警类型：</label>
		                <div class="col-sm-9">
                            <select class="form-control" id="alarm_type">
                              <option value="0">进</option>
                              <option value="1">出</option>
                              <option value="2" selected>进出</option>
                            </select>
		                </div>
	                </div>
                    <div class="form-group">
		                <label for="time_limit_flag" class="col-sm-3 control-label">限时：</label>
		                <div class="col-sm-9">
                            <select class="form-control" id="time_limit_flag">
                              <option value="0" selected>不限制</option>
                              @*<option value="1">限制</option>*@
                            </select>
		                </div>
	                </div>
                    <div class="form-group" style="display:none" id="limit_flag_time">
		                <label for="lastname" class="col-sm-3 control-label">开始时间：</label>
                        <div class="col-sm-3">
			                <input type="text" class="form-control" id="beginTime" value=" " placeholder="开始时间">
                        </div>
                        <label for="lastname" class="col-sm-2 control-label">结束时间</label>
                        <div class="col-sm-4">
			                <input type="text" class="form-control" id="endTime" value=" " placeholder="结束时间">
                        </div>
	                </div>
                </form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" 
						data-dismiss="modal">关闭
				</button>
				<button type="button" class="btn btn-primary" onclick="btn_save();">
					保存
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<div class='button-group' style="background-color: #0d9bf2;right: 600px;top: 20px;height:45px;">
        <input id="cityName" class="inputtext" placeholder="请输入城市的名称" type="text"/>
        <input id="query" class="button" value="搜索" type="button"/>
</div>

<script>
    var keeperUserList;
    $(document).ready(function () {
        keeperUserList=$('#example').dataTable({
            "searching": true,
            "paging": true,
            "ordering": false,
            "info": false,
            "pagingType": "simple_numbers",
            "oLanguage": {//下面是一些汉语翻译
                "sSearch": "搜索",
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "没有检索到数据",
                "sInfo": "显示 _START_ 至 _END_ 条 &nbsp;&nbsp;共 _TOTAL_ 条",
                "sInfoFiltered": "(筛选自 _MAX_ 条数据)",
                "sInfoEmtpy": "没有数据",
                "sProcessing": "正在加载数据...",
                "sProcessing": "<img src='{{rootUrl}}global/img/ajaxLoader/loader01.gif' />", //这里是给服务器发请求后到等待时间显示的 加载gif
                "oPaginate":
                {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "末页"
                }
            },
            "bServerSide": true,
            "sAjaxSource": "@Url.Content("~/StrokeModule/TFence/DataTablePageListJson")",
            "aoColumns": [ //这个属性下的设置会应用到所有列，按顺序没有是空
                { "sDefaultContent": '', "sClass": "action" },//sClass 表示给本列加class
                { "mData": 'uid' }, //mData 表示发请求时候本列的列明，返回的数据中相同下标名字的数据会填充到这一列
                { "mData": 'name' }
                    
            ],
            "fnRowCallback": function (nRow, aData, iDisplayIndex) {// 当创建了行，但还未绘制到屏幕上的时候调用，通常用于改变行的class风格 
                $('td:eq(0)', nRow).html("<a href='javascript:void(0);' onclick='btnCircle(\"" + aData.id + "\")' class='ace_detail'>显示</a>&nbsp;" + "<a href='javascript:void(0);' onclick='btnEdit(\"" + aData.id + "\")' class='ace_detail'>修改</a>&nbsp;" + "<a href='javascript:void(0);' onclick='btnDelete(\"" + aData.id + "\")' class='ace_detail'>删除</a>");
                return nRow;
            }

        });
    });

    var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom:14
    });

    //'en', 'zh_en', 'zh_cn'
    //map.setLang("en");
    var mouseTool = new AMap.MouseTool(map);

    AMap.event.addListener(mouseTool, "draw", function callback(e) {
        var eObject = e.obj;//obj属性就是鼠标事件完成所绘制的覆盖物对象。
        console.log(eObject);
        if (eObject.CLASS_NAME == "AMap.Circle") { //圆形
            var radius = eObject.Hi.radius;
            var lat = eObject.Hi.center["lat"];
            var lng = eObject.Hi.center["lng"];
            var detail = "{radius:" + radius + ",lat:" + lat + ",lng:" + lng + "}";
            $("#vertexes").val(detail);
            console.log(detail);
        } else if (eObject.CLASS_NAME == "AMap.Polygon") { //多边形
            var path = JSON.stringify(eObject.Hi.path);
            $("#vertexes").val(path);
            console.log(path);
        }
        $("#areaModal").modal('show');
    });

    var scale = new AMap.Scale({
        visible: true
    });
    map.addControl(scale);

    var toolBar = new AMap.ToolBar({
        visible: true
    });
    map.addControl(toolBar);

    var overView = new AMap.OverView({
        visible: true
    });
    map.addControl(overView);

    //设置城市
    AMap.event.addDomListener(document.getElementById("query"), "click", function () {
        var cityName = document.getElementById('cityName').value;
        if (!cityName) {
            cityName = '北京市';
        }
        map.setCity(cityName);
    });

    //为地图注册click事件获取鼠标点击出的经纬度坐标
    var clickEventListener = map.on('click', function (e) {
        document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
    });

    var auto = new AMap.Autocomplete({
        input: "tipinput"
    });

    AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
    function select(e) {
        if (e.poi && e.poi.location) {
            map.setZoom(15);
            map.setCenter(e.poi.location);
        }
    }
    //0圆形，1矩形，2多边形
    var btnRectListener = AMap.event.addDomListener(document.getElementById("btnRect"), 'click', function () {
        $("#shape_type").val(1);
        $("#shape_typeVal").val("矩形");
        $('#myModal').modal('hide');
        mouseTool.rectangle();
    });//给div绑定单击事件
    var btnCircleListener = AMap.event.addDomListener(document.getElementById("btnCircle"), 'click', function () {
        $("#shape_type").val(0);
        $("#shape_typeVal").val("圆形");
        $('#myModal').modal('hide');
        mouseTool.circle();
    });//给div绑定单击事件
    var btnAreaListener = AMap.event.addDomListener(document.getElementById("btnArea"), 'click', function () {
        $("#shape_type").val(2);
        $("#shape_typeVal").val("多边形");
        $('#myModal').modal('hide');
        mouseTool.measureArea();
    });//给div绑定单击事件
    //btnCircle();

    //
    function btnCircle(id) {
        Loading(true, "正在提交数据...");
        AjaxJson("/StrokeModule/TFence/SetForm?KeyValue=" + id, {}, function (data) {
            //tipDialog(data.Message, 3, data.Code);
            if (data.vertexes) {
                if (data.shape_type == 0) {
                    drawCircle(data)
                } else if (data.shape_type == 1 || data.shape_type == 2) {
                    drawPolygon(data)
                }
            }
            Loading(false);
            //$('#areaModal').modal('hide');
        });
        
    }

    //画圆
    function drawCircle(data) {
        var contextMenu = new AMap.ContextMenu();  //创建右键菜单
        //右键放大
        contextMenu.addItem("编辑围栏", function () {
            circleEditor.open();
        }, 0);
        //右键缩小
        contextMenu.addItem("保存围栏", function () {
            console.log(circle);
            var id = circle.Hi.id;
            var radius = circle.Hi.radius;
            var lat = circle.Hi.center["lat"];
            var lng = circle.Hi.center["lng"];
            var vertexes = "{radius:" + radius + ",lat:" + lat + ",lng:" + lng + "}";
            AjaxJson("/StrokeModule/TFence/SubmitForm", { vertexes: vertexes, KeyValue: id }, function (data) {
                if (data.Code == "1") {
                    //$('#areaModal').modal('hide');
                    circleEditor.close();
                    circle.hide();
                }
                tipDialog(data.Message, 3, data.Code);
            });
        }, 1);
        //右键缩小
        contextMenu.addItem("取消编辑", function () {
            circleEditor.close();
        }, 2);
        //右键缩小
        contextMenu.addItem("关闭", function () {
            circleEditor.close();
            circle.hide();
        }, 3);
        var obj = eval('(' + data.vertexes + ')');
        var circle = new AMap.Circle({
            id: data.id,
            center: new AMap.LngLat(obj.lng, obj.lat),// 圆心位置
            radius: obj.radius, //半径
            strokeColor: "#F33", //线颜色
            strokeOpacity: 0.5, //线透明度
            strokeWeight: 3, //线粗细度
            fillColor: "#ee2200", //填充颜色
            fillOpacity: 0.35//填充透明度
        });
        map.setZoom(14);
        var circleEditor = new AMap.CircleEditor(map, circle);
        circle.setMap(map);
        map.setCenter([obj.lng, obj.lat]);
        map.setFitView();
        circle.on('rightclick', function (e) {
            contextMenu.open(map, e.lnglat);
        });
    }

    //drawPolygon();
    //画多边形
    function drawPolygon(data) {
        var contextMenu = new AMap.ContextMenu();  //创建右键菜单
        //右键放大
        contextMenu.addItem("编辑围栏", function () {
            polygonEditor.open();
        }, 0);
        //右键缩小
        contextMenu.addItem("保存围栏", function () {
            console.log(polygon);
            polygon.hide();
        }, 1);
        //右键缩小
        contextMenu.addItem("取消编辑", function () {
            polygonEditor.close();
        }, 2);
        //右键缩小
        contextMenu.addItem("关闭", function () {
            polygon.hide();
        }, 3);
        var obj = eval(data.vertexes);
        var polygonArr = new Array();//多边形覆盖物节点坐标数组
        for (var i = 0; i < obj.length; i++) {
            polygonArr.push([obj[i].lng, obj[i].lat]);
        }
        //polygonArr.push([116.403322, 39.920255]);
        //polygonArr.push([116.410703, 39.897555]);
        //polygonArr.push([116.402292, 39.892353]);
        //polygonArr.push([116.389846, 39.891365]);
        var polygon = new AMap.Polygon({
           
            path: polygonArr,//设置多边形边界路径
            strokeColor: "#FF33FF", //线颜色
            strokeOpacity: 0.5, //线透明度
            strokeWeight: 3,    //线宽
            fillColor: "#ee2200", //填充色
            fillOpacity: 0.35//填充透明度
        });
        map.setZoom(14);
        polygon.setMap(map);
        var polygonEditor = new AMap.PolyEditor(map, polygon);
        polygon.on('rightclick', function (e) {
            contextMenu.open(map, e.lnglat);
        });
    }

    $(function () {
        $('#areaModal').on('hide.bs.modal',
        function () {
            mouseTool.close(true);
        })
    });
    function btn_save() {
        var uid = $("#uid").val();
        var name = $("#name").val();
        if (!uid || !name) {
            tipDialog("用户编码和围栏名称必须填写！", 3, 0);
            return;
        }
        Loading(true, "正在提交数据...");
        window.setTimeout(function () {
            var postData = GetWebControls("#form1");
            AjaxJson("/StrokeModule/TFence/SubmitForm?KeyValue=" + $("#id").val(), postData, function (data) {
                tipDialog(data.Message, 3, data.Code);
                $('#example').dataTable().api().ajax.reload();
                $('#areaModal').modal('hide');
            });
        }, 200); 
    }

    function btnEdit(id) {
        Loading(true, "正在提交数据...");
        AjaxJson("/StrokeModule/TFence/SetForm?KeyValue=" + id, {}, function (data) {
            //tipDialog(data.Message, 3, data.Code);
            SetWebControls(data);
            Loading(false);
            $('#areaModal').modal('show');
        });
    }

    function btnDelete(id) {
        Loading(true, "正在提交数据...");
        window.setTimeout(function () {
            var postData = GetWebControls("#form1");
            AjaxJson("/StrokeModule/TFence/Delete?KeyValue=" + id, {}, function (data) {
                tipDialog(data.Message, 3, data.Code);
                keeperUserList.api().ajax.reload();
                //$('#areaModal').modal('hide');
            });
        }, 200);
    }

</script>
</body>
</html>
